﻿#region File Description

//-----------------------------------------------------------------------------
// RentitController.cs
//
// Author: ITU Team3 (2012)
//-----------------------------------------------------------------------------

#endregion File Description

#region Using Statements

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using rentit03_client.Models;
using rentit03_client.rentit03;

#endregion

namespace rentit03_client.Controllers
{
    public class RentitController : Controller
    {
        private UserObj _user;

        /// <summary>
        /// Returns the session ID of a user of one is logged in.
        /// </summary>
        protected static string Sid
        {
            get
            {
                return System.Web.HttpContext.Current.Session["Sid"] == null ? "" : System.Web.HttpContext.Current.Session["Sid"] as string;
            }
            set
            {
                System.Web.HttpContext.Current.Session["Sid"] = value;
            }
        }

        /// <summary>
        /// Gets a new <seealso cref="UserObj"/>.
        /// </summary>
        protected new UserObj User
        {
            get
            {
                if (_user != null)
                    return _user;

                var r = new ServiceClient().ReadUserFromSession(Sid);
                var ro = MagicJSON.Deserialize<ReturnObj>(r);

                if (ro.Success)
                {
                    var user = MagicJSON.Deserialize<UserObj>(ro.Value);
                    System.Web.HttpContext.Current.Session["User"] = user;
                    _user = user;
                    return user;
                }

                if (ro.Status == 102)
                {
                    Sid = "";
                    return new UserObj();
                }

                throw new Exception("Could not load user! " + r);
            }
        }

        /// <summary>
        /// Called after the action method is invoked.
        /// </summary>
        /// <param name="filterContext">The <seealso cref="ActionExecutingContext"/> of the action method.</param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            ViewBag.User = User;
            ViewBag.Cart = new CartController().GetCart();
        }
    }
}